package com.headwind.logistics.common.listener;

import com.headwind.logistics.common.util.RedisUtils;
import com.headwind.logistics.system.mapper.CouponMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;

/**
 * @Author 小恶魔
 * @Date 2020-07-23 9:55
 * @Version 1.0
 * @DESCRIPTION redis Key过期监听
 */
public class KeyExpiredListener extends KeyExpirationEventMessageListener {

    @Resource
    private CouponMapper couponMapper;

    private RedisUtils redisUtils;

    private static final Logger LOGGER = LoggerFactory.getLogger(KeyExpiredListener.class);

    public KeyExpiredListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }

    /**
     * 监听过期的key
     * @param message
     * @param pattern
     */
    @Override
    public void onMessage(Message message, byte[] pattern) {
        String channel = new String(message.getChannel(), StandardCharsets.UTF_8);
        //过期的key
        String key = new String(message.getBody(),StandardCharsets.UTF_8);
        int are= Integer.parseInt(key);
        couponMapper.updateCustomer(are);

        LOGGER.info("redis key 过期：pattern={},channel={},key={}",new String(pattern),channel,key);
    }
}
